let depts = [
    { id: 1, name: "集团", pid: null }, 
    { id: 2, name: "子公司", pid: 1 }, 
    { id: 3, name: "财务部门", pid: 2 }
]

/**
 * 第一次调用fn的时候，children = [{id:1,name:"集团",children:fn()}]
 * 第二次调用fn的时候，
 * @param {*} data 
 * @param {*} rootId 
 * @returns 
 */
function fn(data, rootId = null) {
    const children = []      //定义一个空数组
    data.forEach(item => {
        if (item.pid === rootId) {    //如果每一项的pid=rootId就添加到数组里
            children.push(item)
            item.children = fn(data, item.id)
        }
    });
    return children
}

const res2 = fn(depts)
console.log(res2);

const res = new Array()
res = null

const data = new Date()
const data2 = data
